package com.qf.fmall2202.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.fmall2202.product.entity.*;
import com.qf.fmall2202.product.service.*;
import com.qf.fmall2202.user.entity.User;
import com.qf.fmall2202.user.service.IUsersService;
import com.qf.fmall2202.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 商品信息相关表：分类表，商品图片表，商品规格表，商品参数表 前端控制器
 * </p>
 *
 * @author dong_
 * @since 2022-11-07
 */
@CrossOrigin
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    IProductService productService;

    @Autowired
    IProductSkuService productSkuService;

    @Autowired
    IProductImgService productImgService;

    @Autowired
    IProductParamsService productParamsService;

    @Autowired
    IProductCommentsService productCommentsService;

    @Autowired
    IUsersService usersService;


    @GetMapping("/detail-commontscount/{productid}")
    public R detailCommontscount(@PathVariable("productid") String productid) {

        final QueryWrapper<ProductComments> productCommentsQueryWrapper = new QueryWrapper<>();
        productCommentsQueryWrapper.select("comm_type,COUNT(1) AS num");
        productCommentsQueryWrapper.eq("product_id", productid);
        productCommentsQueryWrapper.groupBy("comm_type");

        final List<Map<String, Object>> commentsList = productCommentsService.listMaps(productCommentsQueryWrapper);

        // 为了在 lambda 表达式中 对局部变量进行赋值的特殊操作
        AtomicReference<Long> goodTotal = new AtomicReference<Long>(0l);
        AtomicReference<Long> badTotal = new AtomicReference<Long>(0l);
        AtomicReference<Long> midTotal = new AtomicReference<Long>(0l);
        commentsList.forEach(
                map -> {
                    final Integer comm_type = (Integer) map.get("comm_type");
                    if (comm_type.equals(-1)) {
                        badTotal.set((Long) map.get("num"));
                    } else if (comm_type.equals(0)) {
                        midTotal.set((Long) map.get("num"));
                    }else if(comm_type.equals(1)) {
                        goodTotal.set((Long) map.get("num"));
                    }
                }
        );

        // 计算好评率
        final Long goodTotalLong = goodTotal.get();
        final Long badTotaLong = badTotal.get();
        final Long midTotalLong = midTotal.get();
        final Long totalLong = goodTotalLong + badTotaLong + midTotalLong;

        // 在java中进行精度运算
        final BigDecimal divide = new BigDecimal(goodTotalLong).multiply(new BigDecimal(100))
                .divide(new BigDecimal(totalLong), 2, RoundingMode.HALF_UP);

        final String percent = divide.toString();

        final HashMap<String, Object> data = new HashMap<>();

        data.put("goodTotal",goodTotalLong);
        data.put("total",totalLong);
        data.put("badTotal",badTotaLong);
        data.put("midTotal",midTotalLong);
        data.put("percent",percent);

        return R.ok().put("data", data);


    }


    @GetMapping("/detail-commonts/{productid}")
    public R detailCommonts(@PathVariable("productid") String productid, Integer pageNum, Integer limit) {

        //1 创建分页对象
        final Page<ProductComments> page = new Page<>(pageNum, limit);

        //2 创建 querywrapper对象
        final LambdaQueryWrapper<ProductComments> queryWrapper = new LambdaQueryWrapper<ProductComments>()
                .eq(ProductComments::getProductId, productid);

        //3 分页查询
        productCommentsService.page(page, queryWrapper);

        final List<ProductComments> commentsList = page.getRecords();

        // 把 ProductComments 中缺少的用户信息 补全
        populate(commentsList);

        //4 准备map封装返回的数据
        final HashMap<String, Object> data = new HashMap<>();
        data.put("pageCount", page.getPages());  // 总页数
        data.put("count", page.getTotal()); // 总条数
        data.put("list", commentsList);   // 当前页 的数据

        return R.ok().put("data", data);

    }


    /**
     * 把缺少 用户信息的 ProductComments 补全用户信息
     *
     * @param commentsList
     */
    private void populate(List<ProductComments> commentsList) {

        //1. 把 commentsList 中的userid对应的用户数据都查询出来
        // List<ProductComments> --->  List<用户ID>
        final List<Integer> userIdList = commentsList.stream().map(productComments -> Integer.valueOf(productComments.getUserId())).collect(Collectors.toList());

        final QueryWrapper<User> queryWrapper = new QueryWrapper<User>().in("user_id", userIdList);

        final List<User> userList = usersService.list(queryWrapper);

        // List<User> --->  Map<用户ID, List<用户>>
//        final Map<Integer, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getUserId));

        final Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(user -> user.getUserId(), user -> user));

        //2. 遍历 commentsList ，为确实的属性赋值
        commentsList.forEach(productComments -> {

            final String userId = productComments.getUserId();

            // 在 userList 中 查找 userId对应的user 对象
            final User user = userMap.get(Integer.valueOf(userId));
//            final User user = users.get(0);

            productComments.setUsername(user.getUsername());
            productComments.setNickname(user.getNickname());
            productComments.setUserImg(user.getUserImg());

        });


    }


    /**
     * 查询商品参数信息
     *
     * @param productid
     * @return
     */
    @GetMapping("/detail-params/{productid}")
    public R detailParams(@PathVariable("productid") String productid) {

        // 查询商品参数信息
        final ProductParams productParams = productParamsService.getOne(new LambdaQueryWrapper<ProductParams>().eq(ProductParams::getProductId, productid));

        return R.ok().put("data", productParams);
    }


    /**
     * 查询商品的基本信息
     *
     * @param productid
     * @return
     */
    @GetMapping("/detail-info/{productid}")
    public R detailInfo(@PathVariable("productid") String productid) {

        final HashMap<String, Object> data = new HashMap<>();

        //1. 查商品基本信息
        final Product product = productService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getProductId, productid));
        data.put("product", product);

        //2. 查询商品的 sku 信息
        final List<ProductSku> skuList = productSkuService
                .list(new LambdaQueryWrapper<ProductSku>()
                        .eq(ProductSku::getProductId, productid)
                        .eq(ProductSku::getStatus, 1));
        data.put("productSkus", skuList);

        //3. 查询商品的图片信息
        final List<ProductImg> imgList = productImgService.list(new LambdaQueryWrapper<ProductImg>().eq(ProductImg::getItemId, productid));
        data.put("productImgs", imgList);

        return R.ok().put("data", data);
    }

}
